﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Configuration;

namespace GDoc.Data.Azure
{

    /// <summary>
    /// Defines a storage set to interact with an azure storage.
    /// </summary>
    /// <typeparam name="T">The type of the entity that this class stores.</typeparam>
    public class StorageSet<T> where T : TableServiceEntity
    {

        private string name;
        private TableServiceContext context;

        /// <summary>
        /// Creates a new set for the type entity.
        /// </summary>
        public StorageSet(string tableName, TableServiceContext context)
        {
            name = tableName;
            this.context = context;
        }

        /// <summary>
        /// The queryable source (mapped) for selects.
        /// </summary>
        public IQueryable<T> Data
        {
            get
            {
                return context.CreateQuery<T>(name);
            }

        }

        /// <summary>
        /// Add an object to the azure context
        /// </summary>
        /// <param name="entity">The entity to add.</param>
        public void Add(T entity)
        {
            context.AddObject(name, entity);
        }

        /// <summary>
        /// Deletes an object from the azure context
        /// </summary>
        /// <param name="entity">The entity to delete.</param>
        public void Delete(T entity)
        {
            context.DeleteObject(entity);
        }

        /// <summary>
        /// Update an object from the azure context
        /// </summary>
        /// <param name="entity">The entity to update.</param>
        public void Update(T entity)
        {
            context.UpdateObject(entity);
        }

        /// <summary>
        /// Async save changes for the current context using the default retry policy.
        /// </summary>
        public void SaveChanges()
        {
            context.SaveChangesWithRetries();
        }

    }
}
